package com.zadtek.sharkRider.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.UserData;
import com.zadtek.sharkRider.frame.JsonProcessHelper;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import cn.jpush.android.api.JPushInterface;

/**
 * ez外卖骑士登录界面
 * 
 * @author Administrator
 * 
 */
@EActivity(R.layout.login)
public class QsLoginActivity extends BaseActivity {

	@ViewById
	ImageView backid; // 返回按钮

	@ViewById
	TextView topview; // 标题

	@ViewById
	EditText log_username, log_passwd; // 用户名,密码

	@ViewById
	Button login_btn; // 登录按钮

	private SharedPreferences sp; // 用户信息缓存
	private Editor editor;

	private Dialog dialog;
	private UserData userdata;

	@AfterViews
	void initViews() {
		topview.setText("登录");
		backid.setVisibility(View.GONE);

		// 判断是否已经登录
		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		String uid = sp.getString("uid", "");
		if (uid != null && !uid.equals("")) {
			Intent intent = new Intent(QsLoginActivity.this, MainActivity.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case Const.STATE_START_SUCCESS: // 登录成功
					closeDialog();
					userdata = (UserData) msg.obj;
					String status = userdata.getStatus();
					if (status != null && status.equals("1")) {
						Common.DisplayToast(QsLoginActivity.this,
								userdata.getMessage(), 1);
						//恢复激光服务
						JPushInterface.resumePush(getApplicationContext());
						// 绑定别名
						String uid = userdata.getUid();
						if (!uid.equals("")) {
							setAlias(uid);
						}
						// 登录成功后,将用户信息存入缓存中
						writeSp();
						Intent intent = new Intent(QsLoginActivity.this,
								MainActivity.class);
						startActivity(intent);
					} else {
						Common.DisplayToast(QsLoginActivity.this,
								userdata.getMessage(), 2);
					}
					break;
				case Const.STATE_START_ERROR:
					closeDialog();
					Common.DisplayToast(QsLoginActivity.this, "通信失败,请检查网络!", 2);
					break;
				case Const.MSG_SET_ALIAS:// 绑定别名
					JPushInterface.setAliasAndTags(getApplicationContext(),
							(String) msg.obj, null, mAliasCallback);
					break;
				}
			}
		};

	}

	// 将用户信息写入缓存中
	private void writeSp() {
		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		editor = sp.edit();
		editor.putString("uid", userdata.getUid());
		editor.putString("uname", userdata.getRealname());
		editor.putString("phone", userdata.getPhone());
		editor.putString("account", userdata.getAccount());
		editor.putString("close", userdata.getClose());
		editor.putString("qsstatus", userdata.getQsstatus());
		editor.commit();
	}

	@Click(R.id.login_btn)
	void loginClick() {
		String uname = log_username.getText().toString();
		String upwd = log_passwd.getText().toString();
		if (!"".equals(upwd.trim()) && !"".equals(uname.trim())) {
			dialog = Common.getTipDialog(QsLoginActivity.this,
					R.layout.loading, 0, 0);
			new LoginRegAsyncTask().execute("login", uname, upwd);
		} else {
			Common.createExitDialog(QsLoginActivity.this, "EZdriver", "请输入用户名和密码!");
		}
	}

	// 关闭dialog
	void closeDialog() {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	// 执行登录,注册
	public class LoginRegAsyncTask extends AsyncTask<String, String, String> {

		private UserData user;

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String res = "";
			if (params[0].equals("login")) {
				user = JsonProcessHelper.jsonProcess_user_login("login_qs",
						params[1], params[2]);
				if (null != user) {
					res = "login_ok";
				} else {
					res = "ping_me_error";
				}

			}

			return res;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result.equals("login_ok")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_SUCCESS;
				msg.obj = user;
				mHandler.sendMessage(msg);
			} else if (result.equals("ping_me_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_ERROR;
				mHandler.sendMessage(msg);
			}
		}

	}

}
